<!--
 * @Author: levi7754 levi7754@163.com
 * @Date: 2025-05-13 10:40:35
 * @LastEditors: levi7754 levi7754@163.com
 * @LastEditTime: 2025-07-03 18:50:31
 * @FilePath: \ruoyi-mall-uniapp\src\sheep\components\ut-form\ut-form.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <view class="ut-form-wrapper">
    <slot name="top" />
    <uni-forms class="ut-form" ref="xform" :modelValue="data" :rules="rules" label-position="top" label-width="100%">
      <uni-forms-item
        v-for="item in items"
        :key="item.field"
        :label="item.label || $t(`field.${item.label || item.field}`)"
        :required="item.required"
        :name="item.field"
        :class="{'ut-item-required': item.required, 'ut-item-disabled': item.disabled || !item.required, 'ut-item-valid': validateList.find(f => f.key === item.field)}"
      >
        <!-- 查询 -->
        <uni-easyinput
          v-if="item.type === 'search'"
          v-model="data[item.field]"
          :placeholder="$t('app.please') + (item.field || item.label)"
          suffixIcon="search"
          class="ut-search-item"
          disabled
          @iconClick="iconClick(item)"
        />
        <!-- 日期 -->
        <uni-datetime-picker
          v-else-if="item.type === 'date'"
          type="date"
          v-model="data[item.field]"
          return-type="string"
          start="2025-01-01"
          end="2049-12-31"
          class="ut-date-picker"
          v-bind="item"
          @change="onChange(item)"
          @show="onShow(item)"
        />
        <!-- 下拉选择 -->
        <uni-data-select
          v-else-if="item.type === 'select'"
          v-model="data[item.field]"
          :localdata="item.localdata"
          :disabled="dataStatus ==='detail' || item.disabled"
          @change="onChange(item)"
        />
        <!-- 数据字典编辑时 -->
        <uni-data-select
        v-else-if="item.dictCode && dataStatus !=='detail' && !item.disabled"
        v-model="data[item.field]"
        :localdata="getLocalData(item.dictCode)"
        :disabled="dataStatus ==='detail' || item.disabled"
        @change="onChange(item)"
        />
        <!-- 数据字典禁用时 -->
        <uni-easyinput
          v-else-if="item.dictCode"
          :value="getDictData(item)"
          disabled
        />
        <!-- 上传组件 -->
        <view v-else-if="item.type === 'upload'">
          <ut-upload :data="data" :field="item.field" :limit="item.limit" :source-table="item.sourceTable" />
        </view>
        <!-- 文本/数字 -->
        <uni-easyinput
          v-else
          v-model="data[item.field]"
          v-bind="item"
          :disabled="item.disabled"
          :placeholder="!item.disabled ? $t('app.please') + (item.label || $t('field.' + item.field)) : ''"
        >
        <template v-if="item.left" #left>
          <view style="padding: 0 6rpx 0 12rpx; font-size: 28rpx; color: #999;">{{ item.left }}</view>
        </template>
        <template v-if="item.right" #right>
          <view style="padding: 0 6rpx 0 12rpx; font-size: 28rpx; color: #999;">{{ item.right }}</view>
        </template>
      </uni-easyinput>
      </uni-forms-item>
    </uni-forms>
    <button
      v-if="showButton"
      class="ss-reset-button udp-btn"
      @tap="onTap()"
    >
      {{ $t("btn." + buttonText) }}
    </button>
  </view>
</template>
<script setup>
import { ref, computed } from "vue"
import { useI18n } from "vue-i18n";
import utUpload from "./ut-upload.vue"
const props = defineProps({
  data: {
    type: Object,
    default() {
      return {}
    }
  },
  items: {
    type: Array,
    default() {
      return [];
    },
  },
  showButton: {
    type: Boolean,
    default: true
  },
  buttonText: {
    type: String,
    default: "save"
  },
  dataStatus: {
    type: String,
    default: "detail"
  },
})

const { t } = useI18n()
const xform = ref(null)
const validateList = ref([])

const rules = computed(() => {
  const rules = {}
	props.items.filter(item => item.required).forEach(item => {
    const msg = `${t('app.please')}${item.field || item.label}`
		if (item.type === 'number') {
			rules[item.field] = { rules:[{ required: true, minimum: 0.001, errorMessage: msg }] }
		} else {
			rules[item.field] = { rules:[{ required: true, errorMessage: msg }] }
		}
	})
  return rules
})

/**
 * 右侧icon点击
 * @param item 表单项
 */
const iconClick = (item) => {
  console.log(item)
  emits('iconClick', item)
}
/**
 * 数值变化
 * @param item 表单项
 */
const onChange = item => {
  emits('change', item)
}
/**
 * 时间显示
 */
const onShow = item => {
  emits('show', item)
}

const onTap = () => {
  xform.value.validate(valid => {
    console.log(valid)
    validateList.value = valid || []
    if (valid) {
      setTimeout(() => {
        xform.value.clearValidate()
        validateList.value = []
      }, 1200);
    } else {
      emits('confirm', props.data)
    }
  })
}

/**
 * 表单提交
 * @param callback 提交回调函数 
 */
const validate = (callback) => {
  xform.value.validate(valid => {
    validateList.value = valid
    callback(valid)
    setTimeout(() => {
        xform.value.clearValidate()
        validateList.value = []
      }, 1200);
  })
}
/**
 * 数据字典下拉
 * @param code 数据字典编码
 */
const getLocalData = (code) => {
  const dict = uni.getStorageSync('kDictData')
  if (!dict[code]) return []
  const list = dict[code].children.map(dict => {
    return { value: dict.dictCode, text: dict.dictName }
  })
  return list
}
/**
 * 数据字典渲染
 * @param item 表单项
 */
const getDictData = (item) => {
  const list = this.getLocalData(item.dictCode)
  const data = list.find(f => f.value === props.data[item.field])
  return data ? data.text : props.data[item.field]
}

const emits = defineEmits(['click', 'confirm', 'change'])

defineExpose({ validate })

</script>

<style lang="scss" scoped>
:deep() {
  .uni-easyinput__content.is-disabled {
    border-color: #efefef !important;
    background-color: #FCFCFC !important;
    color: #000;
  }
  .uni-easyinput__content-input {
    padding-left: 12rpx !important;
  }
  .ut-item-disabled .uni-forms-item__inner {
    padding-bottom: 6rpx;
  }
  .ut-search-item {
    .uni-easyinput__content.is-disabled {
      border-color: #efefef !important;
      background-color: #fff !important;
      color: #000;
    }
  }
  .ut-item-valid {
    margin-bottom: 44rpx !important;
  }
  .uni-forms-item {
    padding-left: 12rpx;
    padding-right: 12rpx;
    margin-bottom: 12rpx;
    .uni-forms-item__label {
      font-weight: 600;
    }
  }
}
.ut-form-wrapper {
  background-color: #fff;
  margin: 16rpx;
  border-radius: 10px;
  padding: 20rpx 12rpx;
}
.udp-btn {
  // width: 668rpx;
  height: 70rpx;
  background: linear-gradient(90deg, #EA0D2C 0%, #f63a53 100%);
  box-shadow: 0px 8rpx 6rpx 0px rgba(255, 104, 4, 0.22);
  border-radius: 24rpx;
  color: #fff;
  margin-left: 12rpx;
  margin-right: 12rpx;
  font-weight: 500;
  font-size: 28rpx;
  line-height: normal;
}
.ut-date-picker {
  ::v-deep .uni-date-editor--x__disabled{
    opacity: 1;
    .uni-date-x {
      color: #000;
      background-color:#f9f9f9;
    }
  }
}
</style>